from flask import Flask, render_template, send_file, request
import mysql.connector
import os

app = Flask(__name__)
app.config.from_pyfile('config.py')


def get_db_connection():
    return mysql.connector.connect(
        host=app.config['DB_HOST'],
        user=app.config['DB_USER'],
        password=app.config['DB_PASSWORD'],
        database=app.config['DB_NAME']
    )


@app.route('/')
def index():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM books")
    books = cursor.fetchall()
    cursor.close()
    conn.close()
    return render_template('index.html', books=books)


@app.route('/bookshelf')
def bookshelf():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM books WHERE id IN (1, 3, 5, 7)")  # 示例书架书籍
    books = cursor.fetchall()
    cursor.close()
    conn.close()
    return render_template('bookshelf.html', books=books, username="kangakng")


@app.route('/profile')
def profile():
    return render_template('profile.html', username="kangakng")


@app.route('/download/<int:book_id>')
def download(book_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT file_path, title FROM books WHERE id = %s", (book_id,))
    book = cursor.fetchone()
    cursor.close()
    conn.close()

    if book:
        # 构建完整的文件路径
        full_path = os.path.join(app.root_path, 'static', book['file_path'])
        if os.path.exists(full_path):
            return send_file(full_path, as_attachment=True, download_name=f"{book['title']}.book")
        return "文件不存在", 404
    return "书籍不存在", 404


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)